﻿using Microsoft.AspNetCore.Http.Extensions;

namespace Digitalmes.WebApi.Infrastructure;

/// <summary>
/// 终结点筛选器。
/// </summary>
public sealed class PerformanceEndpointFilter(ILogger<PerformanceEndpointFilter> logger) : IEndpointFilter
{
    private readonly Stopwatch _timer = new();

    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
    {
        _timer.Start();

        var result = await next(context);

        _timer.Stop();

        logger.LogInformation("Http request [{Method}]: {Query}, Elapsed: {Elapsed}ms", 
            context.HttpContext.Request.Method,
            context.HttpContext.Request.GetEncodedPathAndQuery(), 
            _timer.ElapsedMilliseconds);

        return result;
    }
}
